package controllers

import (
	"cld-quick-cli/com"
	"cld-quick-cli/logic"
	"cld-quick-cli/pkg"
	"cld-quick-cli/router/middlewares"
	"cld-quick-cli/router/parameters"
	"github.com/gin-gonic/gin"
)

func SendNewPost() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		var np parameters.SendNewPostParams
		// 1. 参数校验！
		err := ctx.ShouldBindJSON(&np)
		if err != nil {
			pkg.ErrorValidator(ctx, err)
			return
		}
		// 2.执行业务逻辑
		userId, exists := ctx.Get(middlewares.CTX_USER_ID)
		if !exists {
			com.ResponseData(ctx, com.CodeNoAuthError, nil)
			return
		}
		np.AuthorId = userId.(string)
		err = logic.SendNewPostLogic(&np)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err.Error())
			return
		}
		com.ResponseData(ctx, com.CodeSuccess, nil)
	}
}
func GetPostDetails() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		// 1. 获取path参数！
		param := ctx.Param("id")
		// 2.调用logic业务
		postDetails, err := logic.GetPostDetailsLogic(param)
		if err != nil {
			com.ResponseData(ctx, com.CodeSuccess, err.Error())
			return
		}
		// 3.返回
		com.ResponseData(ctx, com.CodeSuccess, postDetails)
	}
}
func GetPostListByFilterParams() func(ctx *gin.Context) {
	var filter parameters.GetPostListByFilterParams
	return func(ctx *gin.Context) {
		// 1.校验传递的分页参数+当前模型的检索数据！
		err := ctx.ShouldBindQuery(&filter) // tag 要有form
		if err != nil {
			pkg.ErrorValidator(ctx, err)
			return
		}
		paramsLogic, err := logic.GetPostListByFilterParamsLogic(&filter)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err.Error())
			return
		}
		com.ResponseData(ctx, com.CodeSuccess, paramsLogic)
	}
}
func VotePost() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		// 1. 校验投票参数！
		var voteParams parameters.VotePostParams
		err := ctx.ShouldBindJSON(&voteParams)
		if err != nil {
			pkg.ErrorValidator(ctx, err)
			return
		}
		// 2. 验证用户！
		value, exists := ctx.Get(middlewares.CTX_USER_ID)
		if !exists {
			com.ResponseData(ctx, com.CodeNoAuthError, nil)
			return
		}
		voteParams.UserId = value.(string)
		// 3. 投票逻辑！
		err = logic.VotePostLogic(&voteParams)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err.Error())
			return
		}
		com.ResponseData(ctx, com.CodeSuccess, voteParams)
	}
}

// GetPostRankByTime 根据发布时间获取排行榜！
func GetPostRankByTime() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
	}
}

// UpdatePost 更新帖子
func UpdatePost() func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		var updateParameters parameters.UpdatePostParams
		err := ctx.ShouldBindJSON(&updateParameters)
		if err != nil {
			pkg.ErrorValidator(ctx, err)
			return
		}
		err = logic.UpdatePostLogic(&updateParameters)
		if err != nil {
			com.ResponseData(ctx, com.CodeFailed, err.Error())
			return
		}
		com.ResponseData(ctx, com.CodeSuccess, nil)
	}
}
